package com.shouxin.attendance.serialport;

import android.text.TextUtils;

import com.shouxin.attendance.constants.CommonConstants;
import com.shouxin.attendance.event.EventCardNumber;
import com.shouxin.attendance.utils.CountDownTimer;

import org.apache.log4j.Logger;
import org.greenrobot.eventbus.EventBus;

import java.util.Locale;
import java.util.concurrent.atomic.AtomicBoolean;

class DataHandler {

	private static final Logger logger = Logger.getLogger(DataHandler.class);

    private static final String NO_DATA = "00000000";

    private final TimerCountDown mTimer;

    private AtomicBoolean swipeSwitch = new AtomicBoolean(false);

    private String port;

    DataHandler(String port) {
        this.port = port;
        mTimer = new TimerCountDown();
    }

    synchronized void onDataReceive(String data) {
        logger.debug("receive swipe card data is : " + data);
        if (TextUtils.isEmpty(data) || data.length() != 28) {
	        logger.error("Swipe card data is invalid! data =>" + data);
	        SendHelper.getInstance().sendAlarmOpenCmd(port);
            return;
        }

        String dataEntry = data.substring(4, 12);
        String dataExit = data.substring(14, 22);

        // 没有出入数据
        if (NO_DATA.equals(dataEntry) && NO_DATA.equals(dataExit)) {
            if (swipeSwitch.get()) {
	            logger.debug("正常刷卡情况下的空数据，忽略...");
            } else {
	            logger.debug("非正常刷卡情况下的空数据，告警...");
	            SendHelper.getInstance().sendAlarmOpenCmd(port);
            }
            return;
        }

        if (!NO_DATA.equals(dataEntry)) {
            mTimer.cancel();
            // 设置刷卡开关为正常刷卡
            swipeSwitch.compareAndSet(false, true);
            // 开启正常刷卡周期
            mTimer.start();
            // 上报刷卡数据
            logger.debug("刷卡进入...");
            String cardNumber = String.format(Locale.getDefault(), "%010d", Long.parseLong(dataEntry, 16));
            EventBus.getDefault().post(new EventCardNumber(CommonConstants.POST_ENTRY, cardNumber, port, System.currentTimeMillis()));
            return;
        }
        if (!NO_DATA.equals(dataExit)) {
            mTimer.cancel();
            // 设置刷卡开关为正常刷卡
            swipeSwitch.compareAndSet(false, true);
            // 开启正常刷卡周期
            mTimer.start();
            // 上报刷卡数据
            logger.debug("刷卡出去...");
            String cardNumber = String.format(Locale.getDefault(), "%010d", Long.parseLong(dataExit, 16));
            EventBus.getDefault().post(new EventCardNumber(CommonConstants.POST_EXIT, cardNumber, port, System.currentTimeMillis()));
        }
    }

    private class TimerCountDown extends CountDownTimer {

        TimerCountDown() {
            super(3000, 3000);
        }

        @Override
        public void onTick(long millisUntilFinished) {
        }

        @Override
        public void onFinish() {
            swipeSwitch.compareAndSet(true, false);
        }
    }
}
